package com.wuming.house.api;

import com.wuming.house.core.BusinessException;
import com.wuming.house.core.HouseType;
import com.wuming.house.core.JsonResult;
import com.wuming.house.model.*;
import com.wuming.house.service.*;
import com.wuming.house.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 首页的接口
 */
@Controller
@RequestMapping("/api/index")
public class IndexApi {

    private static Logger logger = LoggerFactory.getLogger(IndexApi.class);

    @Autowired
    private GoodsCateService goodsCateService;

    @Autowired
    private HousepriceService housepriceService;

    @Autowired
    private BannerService bannerService;

    @Autowired
    private GoodsGroupService goodsGroupService;

    @Autowired
    private GroupHouseService groupHouseService;

    @Autowired
    private HouseCommentService houseCommentService;

    @Autowired
    private SecondhouseService secondhouseService;

    @Autowired
    private HouseTagService houseTagService;

    /**
     * 查询出所有的一级分类
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/cate/all", method = RequestMethod.GET)
    public JsonResult getAllCates() {
        try {
            //查询所有的
            List<GoodsCate> cates = goodsCateService.getGoodsCatesByPId(0);
            return new JsonResult(cates, "查询所有分类成功.", true);
        } catch (BusinessException be) {
            logger.error("查询所有分类失败,异常:{}", be.getMessage());
            return new JsonResult(null, "查询所有分类失败.", false);
        } catch (Exception e) {
            logger.error("查询所有分类失败,异常:{}", e.getMessage());
            return new JsonResult(null, "查询所有分类失败.", false);
        }
    }


    /**
     * 根据城市查询出城市房价信息
     *
     * @param city 城市
     * @return 城市房价信息
     */
    @ResponseBody
    @RequestMapping(value = "/houseprice/get", method = RequestMethod.GET)
    public JsonResult getCurrentMonthHouseprice(@RequestParam String city) {
        try {
            //查询城市房价信息
            Calendar current = Calendar.getInstance();
            Integer currentYear = current.get(Calendar.YEAR);
            Integer currentMonth = current.get(Calendar.MONTH) + 1;
            Date lastMonthDate = DateUtil.addMonth(-1);
            Calendar last = Calendar.getInstance();
            last.setTime(lastMonthDate);
            Integer lastCurrentYear = last.get(Calendar.YEAR);
            Integer lastCurrentMonth = last.get(Calendar.MONTH) + 1;
            List<Houseprice> houseprices = housepriceService.getHousepriceByCity(city, currentYear, currentMonth);
            if (null == houseprices || houseprices.isEmpty()) {
                return new JsonResult(null, "不存在当月房价信息.", false);
            }
            Houseprice hp = houseprices.get(0);
            List<Houseprice> lasthouseprices = housepriceService.getHousepriceByCity(city, lastCurrentYear, lastCurrentMonth);
            if (null != lasthouseprices && !lasthouseprices.isEmpty()) {
                Houseprice lasthp = lasthouseprices.get(0);
                hp.setLastNewhousePrice(lasthp.getNewhousePrice());
                hp.setLastSecondhousePrice(lasthp.getSecondhousePrice());
            }
            DecimalFormat df = new DecimalFormat("0.00");
            hp.setNewHouseRatio(df.format((hp.getNewhousePrice() - hp.getLastNewhousePrice()) * 1.00 / hp.getLastNewhousePrice()));
            hp.setSecondHouseRatio(df.format((hp.getSecondhousePrice() - hp.getLastSecondhousePrice()) * 1.00 / hp.getLastSecondhousePrice()));
            hp.setNewHouseOperate(getHousepriceOperate(hp.getNewhousePrice(), hp.getLastNewhousePrice()));
            hp.setSecondHouseOperate(getHousepriceOperate(hp.getSecondhousePrice(), hp.getLastSecondhousePrice()));
            return new JsonResult(hp, "查询城市房价信息成功.", true);
        } catch (BusinessException be) {
            logger.error("查询城市房价信息失败,异常:{}", be.getMessage());
            return new JsonResult(null, "查询城市房价信息失败.", false);
        } catch (Exception e) {
            logger.error("查询城市房价信息失败,异常:{}", e.getMessage());
            return new JsonResult(null, "查询城市房价信息失败.", false);
        }
    }


    private String getHousepriceOperate(Integer currentPrice, Integer lastPrice) {
        if (lastPrice < currentPrice) {
            return "+";
        } else if (lastPrice > currentPrice) {
            return "-";
        } else {
            return "=";
        }
    }


    /**
     * 查询首页的广告信息
     *
     * @param type 广告类型
     * @return 城市房价信息
     */
    @ResponseBody
    @RequestMapping(value = "/banner/get/{type}", method = RequestMethod.GET)
    public JsonResult getBannerByType(@PathVariable Integer type) {
        try {
            //查询首页广告信息
            List<Banner> banners = bannerService.getAllBannerByType(type);
            return new JsonResult(banners, "查询广告信息成功.", true);
        } catch (BusinessException be) {
            logger.error("查询广告信息失败,异常:{}", be.getMessage());
            return new JsonResult(null, "查询广告信息失败.", false);
        } catch (Exception e) {
            logger.error("查询广告信息失败,异常:{}", e.getMessage());
            return new JsonResult(null, "查询广告信息失败.", false);
        }
    }

    /**
     * 根据分组查询房产信息
     *
     * @param groupType 分组类型
     * @return 分组房产信息
     */
    @ResponseBody
    @RequestMapping(value = "/group/house/{groupType}", method = RequestMethod.GET)
    public JsonResult getHouseByGroup(@PathVariable Integer groupType, @RequestParam(defaultValue = "0") int pageIndex,
                                      @RequestParam(defaultValue = "10") int pageSize) {
        try {
            //查询首页分组房产信息
            GoodsGroup gg = goodsGroupService.getGoodsGroupByType(groupType);
            if (null == gg) {
                return new JsonResult(null, "分组类型不存在.", false);
            }
            List<GroupHouse> groupHouses = groupHouseService.getHouseByGroupId(gg.getId(), pageIndex, pageSize);
            for (GroupHouse gh : groupHouses) {
                House house = gh.getHouse();
                List<HouseComment> comments = houseCommentService.selectHouseCommentsByPage(null, null, house.getId(), null,1,99999);
                if (null != comments && !comments.isEmpty()) {
                    house.setCommentNum(comments.size());
                    house.setScore(houseCommentService.getScoreByHouseComments(comments));
                } else {
                    house.setCommentNum(0);
                    house.setScore(0);
                }
                List<HouseTag> houseTags = houseTagService.getHouseTagByHouseId(house.getId(), HouseType.NEW_HOUSE.getValue().intValue());
                house.setHouseTags(houseTags);
            }
            return new JsonResult(groupHouses, "查询分组房产信息成功.", true);
        } catch (BusinessException be) {
            logger.error("查询分组房产信息失败,异常:{}", be.getMessage());
            return new JsonResult(null, "查询分组房产信息失败.", false);
        } catch (Exception e) {
            logger.error("查询分组房产信息失败,异常:{}", e.getMessage());
            return new JsonResult(null, "查询分组房产信息失败.", false);
        }
    }

    /**
     * 根据分组查询房产信息
     *
     * @return 分组房产信息
     */
    @ResponseBody
    @RequestMapping(value = "/group/secondhouse/{groupId}", method = RequestMethod.GET)
    public JsonResult getSecondHouseByGroup(@PathVariable Long groupId) {
        try {
            //查询首页分组房产信息
            List<GroupHouse> groupHouses = groupHouseService.getAllGroupHousesByParams(groupId);
            List<Secondhouse> secondhouses = new ArrayList<>();
            for (GroupHouse gh : groupHouses) {
                Secondhouse sh = secondhouseService.getSecondhouseById(gh.getHouseId());
                List<HouseTag> houseTags = houseTagService.getHouseTagByHouseId(sh.getId(), HouseType.SECOND_HOUSE.getValue().intValue());
                sh.setHouseTags(houseTags);
                secondhouses.add(sh);
            }
            return new JsonResult(secondhouses, "查询分组房产信息成功.", true);
        } catch (BusinessException be) {
            logger.error("查询分组房产信息失败,异常:{}", be.getMessage());
            return new JsonResult(null, "查询分组房产信息失败.", false);
        } catch (Exception e) {
            logger.error("查询分组房产信息失败,异常:{}", e.getMessage());
            return new JsonResult(null, "查询分组房产信息失败.", false);
        }
    }
}
